package com.magiccompass.alipay.barcode.signature;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.magiccompass.alipay.barcode.constants.AlipayPartnerConstants;

public class MD5SignatureValidation {
	static Logger logger = LogManager.getLogger(MD5SignatureValidation.class.getName());
	public static boolean md5Check(Map<String, String> params){
		String sign = params.get("sign");
		String content = getSignCheckContent(params);
		return verifySign(content, sign);
	}
	
	public static String getSignCheckContent(Map<String, String> params){
		if (params == null) {
            return null;
        }
        params.remove("sign");
        params.remove("sign_type");
        
        StringBuffer content = new StringBuffer();
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);

        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            content.append((i == 0 ? "" : "&") + key + "=" + value);
        }        
        return content.toString()+AlipayPartnerConstants.MD_SALT;
	}
	
	private static boolean verifySign(String signContent, String sign){
		boolean returnFlag = false;
		try {
			String signContentMD5Value = MD5Signature.getMD5String(signContent);
			logger.info("-=-=-= Alipay submit sign is:"+sign);
			logger.info("-=-=-= we make sign is:"+signContentMD5Value);
			returnFlag = sign.equals(signContentMD5Value);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return returnFlag;
	}
}
